package cn.iocoder.an.module.mold.service.linestopregistration;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.an.module.system.api.notify.NotifyMessageSendApi;
import cn.iocoder.an.module.system.api.notify.dto.NotifySendSingleToUserReqDTO;
import cn.iocoder.an.module.system.dal.dataobject.dept.DeptDO;
import cn.iocoder.an.module.system.dal.dataobject.dict.DictDataDO;
import cn.iocoder.an.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.an.module.system.service.dict.DictDataService;
import cn.iocoder.an.module.system.service.user.AdminUserService;
import cn.iocoder.an.module.system.service.dept.DeptService;
import com.google.common.base.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import cn.iocoder.an.module.mold.controller.admin.linestopregistration.vo.*;
import cn.iocoder.an.module.mold.dal.dataobject.linestopregistration.LinestopRegistrationDO;
import cn.iocoder.an.framework.common.pojo.PageResult;
import cn.iocoder.an.framework.common.pojo.PageParam;
import cn.iocoder.an.framework.common.util.object.BeanUtils;

import cn.iocoder.an.module.mold.dal.mysql.linestopregistration.LinestopRegistrationMapper;

import static cn.iocoder.an.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.an.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.an.framework.common.util.collection.CollectionUtils.diffList;
import static cn.iocoder.an.module.mold.enums.ErrorCodeConstants.*;

import cn.iocoder.an.module.business.utils.WeComMessageUtil;

/**
 * 停线登记 Service 实现类
 *
 * @author 芋道源码
 *
 */
@Service
@Validated
public class LinestopRegistrationServiceImpl implements LinestopRegistrationService {

    @Resource
    private LinestopRegistrationMapper linestopRegistrationMapper;

    @Autowired
    private WeComMessageUtil weComMessageUtil;

    @Resource
    private AdminUserService userService;

    @Resource
    private DictDataService dictDataService;

    @Resource
    private DeptService deptService;


    @Resource
    private NotifyMessageSendApi notifySendApi;

    @Override
    public Long createLinestopRegistration(LinestopRegistrationSaveReqVO createReqVO) {
        //根据用户respersonids,  查询所有用户的name，用逗号拼接字符串，存到respersons
        List<Long> respersonids = createReqVO.getRespersonids();
        if (CollUtil.isNotEmpty(respersonids)) {
            List<AdminUserDO> users = userService.getUserList(respersonids);
            // 如果用户列表为空，抛出异常
            if (!users.isEmpty()) {
                // 将用户的姓名拼接成字符串
                String respersons = users.stream()
                        .map(AdminUserDO::getNickname)  // 获取用户姓名
                        .collect(Collectors.joining(", ")); // 使用逗号分隔
                // 设置到 createReqVO 中
                createReqVO.setRespersons(respersons);
            }
        }

        // 插入
        LinestopRegistrationDO linestopRegistration = BeanUtils.toBean(createReqVO, LinestopRegistrationDO.class);
        linestopRegistrationMapper.insert(linestopRegistration);

        String workshopName = linestopRegistration.getWorkshopName();
        var dept = new DeptDO();
        if (workshopName != null && !workshopName.isEmpty()) {
            try {
                Long deptId = Long.valueOf(workshopName);
                dept = deptService.getDept(deptId);
            } catch (NumberFormatException e) {
                // 处理转换异常，如记录日志或抛出自定义异常
                System.err.println("Failed to convert workshopName to Long: " + workshopName);
            }
        }

       // sendMessage(linestopRegistration.getRespersonids(), dept.getName());
        sendMessageWithDetail(linestopRegistration.getRespersonids(), linestopRegistration);
        // 返回
        return linestopRegistration.getId();
    }

    @Override
    public void updateLinestopRegistration(LinestopRegistrationSaveReqVO updateReqVO) {
        // 校验存在
        validateLinestopRegistrationExists(updateReqVO.getId());
        // 更新
        LinestopRegistrationDO updateObj = BeanUtils.toBean(updateReqVO, LinestopRegistrationDO.class);
        //打印属性
     /*   updateObj.setEndTime(updateReqVO.getEndTime());
        updateObj.setDuration(updateReqVO.getDuration());
        System.out.println("更新停线登记信息: " + updateObj.toString());*/
        linestopRegistrationMapper.updateById(updateObj);
    }

    @Override
    public void deleteLinestopRegistration(Long id) {
        // 校验存在
        validateLinestopRegistrationExists(id);
        // 删除
        linestopRegistrationMapper.deleteById(id);
    }

    @Override
    public void deleteLinestopRegistrationListByIds(List<Long> ids) {
        // 删除
        linestopRegistrationMapper.deleteByIds(ids);
    }


    private void validateLinestopRegistrationExists(Long id) {
        if (linestopRegistrationMapper.selectById(id) == null) {
            throw exception(LINESTOP_REGISTRATION_NOT_EXISTS);
        }
    }

    @Override
    public LinestopRegistrationDO getLinestopRegistration(Long id) {
        return linestopRegistrationMapper.selectById(id);
    }

    @Override
    public PageResult<LinestopRegistrationDO> getLinestopRegistrationPage(LinestopRegistrationPageReqVO pageReqVO) {
        return linestopRegistrationMapper.selectPage(pageReqVO);
    }


    //推送企业微信消息 系统内消息推送
    public void sendMessage(List<Long> dutyUserId, String workshopName) {
        //推送消息
        List<AdminUserDO> userList = userService.getUserList(dutyUserId);
        String userIds = "";
        StringBuilder userIdBuilder = new StringBuilder();
        for (AdminUserDO user : userList) {
            // 1. 推送系统消息 准备参数
            String templateCode = "wx-lsp-1"; // 站内信模版，记得在【站内信管理】中配置噢
            Map<String, Object> templateParams = new HashMap<>();
            templateParams.put("linestopname", workshopName);
            NotifySendSingleToUserReqDTO sendToUserDTO = new NotifySendSingleToUserReqDTO();
            sendToUserDTO.setUserId(user.getId());
            sendToUserDTO.setTemplateCode(templateCode);
            sendToUserDTO.setTemplateParams(templateParams);
            Long l = notifySendApi.sendSingleMessageToAdmin(sendToUserDTO);
            System.out.printf("系统内消息通知:", l);

            String userId = weComMessageUtil.getUserIdByMobile(user.getEnterpriseWeChatAccount());
            if (userId != null && !userId.trim().isEmpty()) {
                // 如果已经有内容了，先添加分隔符
                if (userIdBuilder.length() > 0) {
                    userIdBuilder.append("|");
                }
                userIdBuilder.append(userId);
            }
        }
        // 将 StringBuilder 转换为最终的字符串
        userIds = userIdBuilder.toString();
        // 可选：检查最终结果是否为空
        if (userIds.isEmpty()) {
            // 处理没有找到任何有效用户ID的情况
            System.out.printf("没有找到任何有效的企业微信 UserID");
            return;
        }
        // 1. 使用 sendTextMessage 方法 (更灵活，可以同时指定用户、部门、标签)
        //从字典配置中获取发送的消息
        //  DictDataDO wxMessage = dictDataService.getDictData("linestop_create_tip", "1");
        //todo ：修改系统通知  停线管理消息推送优化，体现哪个产线的提出人报的什么停线问题，什么时间开始停线的
        String systemMessage = "停线登记已创建，停线名称：" + workshopName + "，请及时处理。";

        // 将时间戳添加到消息中
        WeComMessageUtil.WeComSendResult weComSendResult = weComMessageUtil.sendTextMessage(systemMessage, userIds, null, null);
        System.out.printf("推送结果:" + weComSendResult.toString());
    }


    //推送企业微信消息 系统内消息推送
    public void sendMessageWithDetail(List<Long> dutyUserId, LinestopRegistrationDO linestopRegistration) {
        //插线，时间，提出人，问题
        String workshopName = linestopRegistration.getWorkshopName();
        var dept = new DeptDO();
        if (workshopName != null && !workshopName.isEmpty()) {
            try {
                Long deptId = Long.valueOf(workshopName);
                dept = deptService.getDept(deptId);
            } catch (NumberFormatException e) {
                System.err.println("Failed to convert workshopName to Long: " + workshopName);
            }
        }

        String proserId = linestopRegistration.getProposer();
        var adminUserDO = new AdminUserDO();
        if (proserId != null && !proserId.isEmpty()) {
            try {
                Long tmp = Long.valueOf(proserId);
                adminUserDO = userService.getUser(tmp);
            } catch (NumberFormatException e) {
                System.err.println("Failed to convert workshopName to Long: " + workshopName);
            }
        }

        //推送消息
        List<AdminUserDO> userList = userService.getUserList(dutyUserId);
        String userIds = "";
        StringBuilder userIdBuilder = new StringBuilder();
        for (AdminUserDO user : userList) {
            // 1. 推送系统消息 准备参数
            String templateCode = "wx-lsp-1"; // 站内信模版，记得在【站内信管理】中配置噢
            Map<String, Object> templateParams = new HashMap<>();
            templateParams.put("linestopname", workshopName);
            NotifySendSingleToUserReqDTO sendToUserDTO = new NotifySendSingleToUserReqDTO();
            sendToUserDTO.setUserId(user.getId());
            sendToUserDTO.setTemplateCode(templateCode);
            sendToUserDTO.setTemplateParams(templateParams);
            Long l = notifySendApi.sendSingleMessageToAdmin(sendToUserDTO);
            System.out.printf("系统内消息通知:", l);

            String userId = weComMessageUtil.getUserIdByMobile(user.getEnterpriseWeChatAccount());
            if (userId != null && !userId.trim().isEmpty()) {
                // 如果已经有内容了，先添加分隔符
                if (userIdBuilder.length() > 0) {
                    userIdBuilder.append("|");
                }
                userIdBuilder.append(userId);
            }
        }
        // 将 StringBuilder 转换为最终的字符串
        userIds = userIdBuilder.toString();
        // 可选：检查最终结果是否为空
        if (userIds.isEmpty()) {
            // 处理没有找到任何有效用户ID的情况
            System.out.printf("没有找到任何有效的企业微信 UserID");
            return;
        }
        // 1. 使用 sendTextMessage 方法 (更灵活，可以同时指定用户、部门、标签)
        //从字典配置中获取发送的消息
        //  DictDataDO wxMessage = dictDataService.getDictData("linestop_create_tip", "1");
        //todo ：修改系统通知  停线管理消息推送优化，体现哪个产线的提出人报的什么停线问题，什么时间开始停线的
        //  停线登记创建提醒： 提出人：{提出人}  停线问题：{停线问题} 时间：开始{时间}。
        String systemMessage = "停线登录创建提醒：产线" + dept.getName() + "已停线，停线开始时间：" + linestopRegistration.getStartTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))+"，提出人：" + adminUserDO.getNickname() + "，停线问题：" + linestopRegistration.getQuestion();

        // 将时间戳添加到消息中
        WeComMessageUtil.WeComSendResult weComSendResult = weComMessageUtil.sendTextMessage(systemMessage, userIds, null, null);
        System.out.printf("推送结果:" + weComSendResult.toString());
    }
}